package hhh.babysleep.presenter;

import android.app.Activity;
import android.app.Application;
import android.database.sqlite.SQLiteDatabase;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import hhh.babysleep.model.dao.DaoMaster;
import hhh.babysleep.model.dao.DaoSession;


/**
 * Created by Administrator on 2017/6/12 0012.
 */
public class MyApp extends Application {
    private static MyApp myApp;
    private static DaoSession daoSession;

    private Map<String,Activity> map=new HashMap<String, Activity>();

    @Override
    public void onCreate() {
        super.onCreate();
        myApp=this;
        setupDatabase();
    }

    private void setupDatabase() {
        DaoMaster.DevOpenHelper helper=new DaoMaster.DevOpenHelper(this,"baby.db",null);
        SQLiteDatabase db=helper.getWritableDatabase();
        DaoMaster daoMaster=new DaoMaster(db);
        daoSession=daoMaster.newSession();
    }

    public static DaoSession getDaoSession(){
        return daoSession;
    }

    public static MyApp getApp(){
        return myApp;
    }

    public Activity get(String name){
        return map.get(name);
    }

    public void put(String name,Activity activity){
        map.put(name,activity);
    }

    public void closeAll(){
        Set<String> names=map.keySet();
        for(String s:names){
            finishActivity(map.get(s));
        }
        map.clear();
    }

    public void remove(String s){
        finishActivity(map.get(s));
    }

    private void finishActivity(Activity activity) {
        if(activity!=null&&!activity.isFinishing()){
            activity.finish();
        }
    }
}
